<template>
  <div class="Preview-container">
    <a-form
      ref="formRef"
      :model="form"
      :layout="formConfig.layout"
      :size="formConfig.size"
      :label-align="formConfig.labelAlign"
    >
      <template v-for="(element, index) in formList" :key="index">
        <FormItem
          @itemConfigDefaultValueChange="itemConfigDefaultValueChange"
          :as-drag="false"
          :item-config="element"
          :index="index"
        ></FormItem>
      </template>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import FormItem from "./FormItem.vue";
import {ref} from "vue";

const props = defineProps({
  data: {
    type: Object,
    default: {
      formConfig: {},
      formList: []
    }
  }
});

const getFormData = (arr: object[]) => {
  let form = {};
  arr.forEach((item: any) => {
    form[item.defaultKey] = item.defaultValue;
  });
  return form;
};
const formRef = ref();
const formConfig = ref(props.data.formConfig);
const formList = ref(props.data.formList);
const form = ref(getFormData(props.data.formList));

const itemConfigDefaultValueChange = (item) => {
  form.value[item.defaultKey] = item.defaultValue;
};

const submit = async () => {
  return formRef.value.validate().then((res) => {
    return form.value;
  });
};

defineExpose({
  submit
});
</script>

<style lang="less" scoped></style>
